extends Node

@export var upgrade_pool_untranslated: Array[AbilityUpgrade]
@export var upgrade_pool: Array[AbilityUpgrade]
@export var upgrade_screen_scene: PackedScene
@export var number_of_options: int = 3  # 每次升级显示的选项数量

@onready var game_manager: Node = $"../../GameManager"

signal enable_upgrade(upgrade:AbilityUpgrade,name:String)

var current_upgrades = {}

func _ready():
	game_manager.level_up.connect(on_level_up)
	
	
	# 加载所有升级资源
	for upgrade in upgrade_pool_untranslated:
		upgrade.name = tr(upgrade.name)
		upgrade.description = tr(upgrade.description)
		
		add_upgrade_to_pool(upgrade)

func on_level_up(current_level: int):
	# 从升级池中选择指定数量的升级
	var chosen_upgrades = get_random_upgrades(number_of_options)
	
	if chosen_upgrades.is_empty():
		return
	
	# 创建升级选择界面
	var upgrade_screen_instance = upgrade_screen_scene.instantiate()
	upgrade_screen_instance.upgrade_selected.connect(on_upgrade_selected)
	add_child(upgrade_screen_instance)
	upgrade_screen_instance.set_ability_upgrades(chosen_upgrades)

func get_random_upgrades(count: int) -> Array[AbilityUpgrade]:
	var available_upgrades = upgrade_pool.duplicate()
	var chosen_upgrades: Array[AbilityUpgrade] = []
	
	# 确保不超过可用升级的数量
	var actual_count = min(count, available_upgrades.size())
	
	# 随机选择指定数量的升级（不重复）
	for i in range(actual_count):
		if available_upgrades.is_empty():
			break
			
		var random_index = randi() % available_upgrades.size()
		var chosen_upgrade = available_upgrades[random_index]
		chosen_upgrades.append(chosen_upgrade)
		
		# 从可用列表中移除已选择的升级，避免重复
		available_upgrades.remove_at(random_index)
	
	return chosen_upgrades

func add_upgrade_to_pool(upgrade: AbilityUpgrade):
	upgrade_pool.append(upgrade)

func on_upgrade_selected(upgrade: AbilityUpgrade):
	enable_upgrade.emit(upgrade)
